/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.mail.controller;

import com.google.appengine.repackaged.org.apache.commons.httpclient.URI;
import com.google.appengine.repackaged.org.apache.commons.httpclient.URIException;

import com.sun.mail.pop3.POP3SSLStore;
import java.io.*;
import java.util.*;
import javax.activation.DataHandler;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.FlagTerm;

import queenb.net.entitybean.M575;
import queenb.web.controller.QueenbController;
import queenb.web.mail.inteface.M575Inf;
import queenb.web.mail.store.M575Store;
import queenb.web.util.ComboboxUtil;
import queenb.web.util.SessionProvider;
import queenb.web.util.Util;
import org.richfaces.model.UploadItem;
import org.richfaces.event.UploadEvent;
import queenb.net.entitybean.*;
import queenb.web.crm.controller.CustomerExpand;
import queenb.web.crm.controller.V030controller;
import queenb.web.crm.store.CustomerStore;
import queenb.web.crm.store.M250Store;
import queenb.web.store.M200Store;
import queenb.web.store.M650Store;
import queenb.web.store.Q000Store;
import queenb.web.store.Q100Store;
import queenb.web.util.*;

/**
 *
 * @author DUYNGUYEN
 */
public class MailExtendController extends QueenbController {

    private ComboboxUtil comboxUtil = new ComboboxUtil();
    private int fb050;
    private M575Inf m575Inf;
    private int pm575;
    private int ff150;
    private String mv576;
    private String mv577;
    private String mv578;
    private String mv579;
    private Date md580 = new Date();
    private int mn581;
    private int fh000;
    private int fh200;
    private int fq100;
    private String fm525 = "A";
    private String mv276 = "FROM";
    private String mv277 = "M";
    private String hoten;
    private String title;
    private String html;
    private String text;
    private int renderMail = 0;
    private Date sendtime;
    private String reload;
    private static int intreload;
    private List<M575> listToFromMail;
    private List<M575> listToFromMailEx;
    private List<M575> listToFromMailSever;
    private String loginGmailYahoo;
    private String passwordGmailYahoo;
    private M575Store m575Store = new M575Store();
    private static Map<Integer, String> map = new HashMap<Integer, String>();
    private List<Map.Entry<Integer, String>> listSendMail;
    private List<ItemMail> listItemMail = new ArrayList<ItemMail>();
    private String fromMail;
    private String toMail;
    private String dateSend;
    private String titleMail;
    private String content;
    private List<ItemMail> listitem = new ArrayList<ItemMail>();
    private String colorchose = "";
    private String stylefrommail = "none";
    //send email 
    private static ArrayList<File> files = new ArrayList<File>();
    private String subjectMail;
    private String contentMail;
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final int SMTP_HOST_PORT = 465;
    private String SMTP_AUTH_USER = "";
    private String SMTP_AUTH_PWD = "";
    private String methodSend = "TO";
    private String listInfo = "";
    private String listInfoTo = "";
    private List<MailItem> listMail = new ArrayList<MailItem>();
    private String s = "";
    private Boolean chkMess = false;
    private Boolean chkMessS = false;
    private String filetemp;
    private String mailBox = "THƯ ĐÃ GỬI";
    // sendEmail for Email
    private int idcus;
    private String emailcus;
    private String typecus;
    private Boolean senper = false;
    private String pageRequest;
    private String check = "E";
    private int sttTitle = 2;
    private M200Store m200Store = new M200Store();
    private int pm200;
    private String listmail;
    private List<SelectItem> listcomboM200;
    private List<SelectItem> listcomboQ000;
    private List<SelectItem> listcomboM250;
    private int typesearchKH;
    private String keysearchKH;
    private List<N100> listdifn100;
    private List<N100> listSelected = new ArrayList<N100>();
    private String mailsend = "";
    private int mailsendId;
    private String mailsendpass = "";
    private String mailrevice = null;
    private int mailreviceId;
    private String mailrevicepass = "";
    M650Store m650Store = new M650Store();
    //paging
    private int Offset = 0;
    private int Limit = 30;
    private int totalrow; // tong so dong
    private int totalpage; // tong so trang
    private int current; // traung hien tai
    static private int numrow = 30; // so dong tren 1 trang
    private int start; // bat dau lay tu record
    private int end; // lay tu record so
    private int startpage = 1; // page bat dau
    private int endpage = 1;   // page ket thuc
    private String pagename = "";
    private int totalcurent;
    private Boolean checkN850 = false;
    private Boolean checkN850pop = false;
    private int numberMail =20;

    public MailExtendController() {
        System.out.println("MailExtendController is called !");
        getKapiMenu().setAdmin(false);

        Object objAction = getRequest().getParameter("action");
        System.out.println("------------action-----------" + objAction);

        Object objpage = getRequest().getParameter("page");
        Object sesspage = SessionProvider.getSessionMapValue("pageaction");
        if (sesspage != null && objpage == null) {
            objpage = sesspage;
            pageRequest = objpage.toString();
        } else if (objpage != null) {
            SessionProvider.setSessionMapValue("pageaction", objpage);
            pageRequest = objpage.toString();
        }


        // save mail for select
        // Object listselect = SessionProvider.getSessionMapValue("listSelectedEx");
        Object listselect = SessionProvider.getSessionMapValue("listSelectedMail");
        if (listselect == null) {
            //SessionProvider.setSessionMapValue("listSelectedEx", listSelected);
            SessionProvider.setSessionMapValue("listSelectedMail", listSelected);
        } else {
            try {
                listSelected = (List<N100>) listselect;
            } catch (Exception e) {
                listSelected = new ArrayList<N100>();
            }
        }
        if (listselect != null) {
            System.out.println("-----list select ----" + listSelected.size());
        }

        Object listBean = SessionProvider.getSessionMapValue("listN100abc");
        if (listBean == null) {
            SessionProvider.setSessionMapValue("listN100abc", listdifn100);
        } else {
            try {
                listdifn100 = (List<N100>) listBean;
            } catch (Exception e) {
                listdifn100 = new ArrayList<N100>();
            }
        }

        getKapiMenu().setMainmenu1("m191"); // Hien thi Menu nao dc chon
        System.out.println("========================================listMail" + listInfo);
        if (objAction != null) {
            if (objAction.equals("come_person")) {
                Object objKey = getRequest().getParameter("key");
                map.remove(Integer.parseInt(objKey.toString()));
                listSendMail = new ArrayList(map.entrySet());
                if (listSendMail != null) {
                    stylefrommail = "block";
                } else {
                    stylefrommail = "none";
                }
                System.out.println("objkey-----------------" + objKey);
            }
            if (objAction.equals("inbox")) {
                Object objInbox = getRequest().getParameter("mv276");
                mailBox = "HỘP THƯ ĐẾN";
                sttTitle = 1;
                SessionProvider.setSessionMapValue("mailBox", mailBox);
                SessionProvider.setSessionMapValue("sttTitle", sttTitle);
                if (objInbox != null) {
                    this.mv276 = objInbox.toString();
//                    listToFromMailEx = getListToFromMailSever();
                }
            }
            if (objAction.equals("outbox")) {

                Object objOutbox = getRequest().getParameter("mv276");
                mailBox = "THƯ ĐÃ GỬI";
                sttTitle = 2;
                SessionProvider.setSessionMapValue("mailBox", mailBox);
                SessionProvider.setSessionMapValue("sttTitle", sttTitle);
                if (objOutbox != null) {
                    this.mv276 = objOutbox.toString();
                    //listToFromMailEx = getListM275Ex(mv276, 0);
                }
            }
            if (objAction.equals("delete")) {
                Object objOutbox = getRequest().getParameter("fm525");
                Object objOutb = getRequest().getParameter("mv276");
                mailBox = "THƯ ĐÃ XÓA";
                sttTitle = 3;
                SessionProvider.setSessionMapValue("mailBox", mailBox);
                SessionProvider.setSessionMapValue("sttTitle", sttTitle);
                if (objOutbox != null && objOutb != null) {
                    System.out.println("Danh sach mail da xoa !");
                    this.fm525 = objOutbox.toString();
                    this.mv276 = objOutb.toString();
                    System.out.println("D:- danh sach mail bị xoa ! getListM275(mv276, 0, fm525): " + mv276 + "," + 0 + " , " + fm525);
                    //listToFromMailEx = getListM275Ex(mv276, 0, fm525);
                }
            }
            if (objAction.equals("maildetail")) {
                Object pnFM575 = getRequest().getParameter("pm575");
                Object objMv276 = getRequest().getParameter("mv276");
                if (objMv276 != null) {
                    System.out.println("-----------------mv272----" + objMv276);
                    this.mv276 = objMv276.toString();
                    listToFromMail = getListM275(mv276, 0);
                }
                colorchose = "#4A5763";
                if (pnFM575 != null) {
                    this.pm575 = Integer.parseInt(pnFM575.toString());
                    List<M575> listDetail = getListM275(mv276, pm575);
                    renderMail = 1;
                    if (listDetail != null) {
                        Iterator iterator = listDetail.iterator();
                        while (iterator.hasNext()) {
                            M575 m575 = (M575) iterator.next();
                            this.pm575 = m575.getPm575();
                            System.out.println("-text--------------------->" + m575.getText());
                            this.mv578 = m575.getText();
                            this.hoten = m575.getHoten();
                            this.title = m575.getTitle();
                            this.sendtime = m575.getSendtime();
                            this.fq100 = m575.getFq100();
                        }
                    }
                }

            }
            if (objAction.equals("reply")) {
                Object objQ100 = getRequest().getParameter("fq100");
                this.fq100 = Integer.parseInt(objQ100.toString());

                Object objTitle = getRequest().getParameter("title");
                this.mv576 = objTitle.toString();
                System.out.println("----------mv576-------------" + mv576);
            }
            if (objAction.equals("addCusp100")) {
                Object f = getRequest().getParameter("p100");
                Object s = getRequest().getParameter("valueC");

                System.out.println("sssssssssssssssss----------------------" + f + "===============" + s);
                if ("false".equals(s.toString())) {
                    for (int i = 0; i < listSelected.size(); i++) {
                        if (listSelected.get(i).pn100 == Integer.parseInt(f.toString())) {
                            listSelected.remove(i);
                            break;
                        }
                    }
                } else {
                    for (int i = 0; i < listdifn100.size(); i++) {
                        if (listdifn100.get(i).pn100 == Integer.parseInt(f.toString())) {
//                            if (list.get(i).getNv105() != null && list.get(i).getNv105() != "" && list.get(i).getNv105().contains("@")) {
                            listSelected.add(listdifn100.get(i));
                            break;
//                            }
                        }
                    }
                }
                SessionProvider.setSessionMapValue("listSelectedMail", listSelected);
                SessionProvider.setSessionMapValue("listN100abc", listdifn100);
                System.out.println("<><><><><><><><><><><><><><><><><><><>-----" + f + "....." + listSelected.size());
                //check All
            } else if (objAction.equals("addAllCusp100")) {
                Object va = getRequest().getParameter("boool");
                if ("true".equals(va.toString())) {
                    listSelected.clear();
                    for (int i = 0; i < listdifn100.size(); i++) {
//                        if (list.get(i).getNv105() != null && list.get(i).getNv105() != "" && list.get(i).getNv105().contains("@")) {
                        listSelected.add(listdifn100.get(i));
//                        }
                    }
                } else {
                    listSelected.clear();
                }
                SessionProvider.setSessionMapValue("listSelectedMail", listSelected);
                SessionProvider.setSessionMapValue("listN100abc", listdifn100);
            } else if (objAction.equals("clear")) {
                listSelected.clear();
                SessionProvider.setSessionMapValue("listSelectedMail", null);
            }

            ////listToFromMail = getListM275(mv276, 0);


        }

        // getparamater for send mail 
//        this.senper=false;
        Q100Store storeQ100 = new Q100Store();
        Object objid = getRequest().getParameter("idx");
        Object objmail = getRequest().getParameter("mailx");
        Object objtype = getRequest().getParameter("typex");
        if (objid != null && objmail != null && objtype != null) {
            try {
                this.idcus = Integer.parseInt(objid.toString());
                this.emailcus = objmail.toString().trim();
                this.typecus = objtype.toString().trim();
                System.out.println("D:- sendmail nhan vien : id:= " + objid.toString() + ", email:= " + objmail.toString());
                if (idcus == -1) {
                    System.out.println("D:- Khong xac dinh duoc id :=" + idcus);
                    idcus = storeQ100.getIdByUserLogin(emailcus);
                    SessionProvider.setSessionMapValue("idcus", idcus);
                    SessionProvider.setSessionMapValue("inout", "I");
                    System.out.println("D:- set id:=" + idcus + " of email: " + emailcus);
                } else {
                    System.out.println("D:- Xac dinh duoc id : " + objid.toString());
                    SessionProvider.setSessionMapValue("idcus", objid);
                    SessionProvider.setSessionMapValue("inout", "E");
                }

                SessionProvider.setSessionMapValue("emailcus", objmail);
                SessionProvider.setSessionMapValue("typecus", objtype);
                this.senper = true;
            } catch (Exception e) {
                System.out.println("D:-- sendmail to person: " + e.getMessage());
                this.idcus = Integer.parseInt("0");
                this.emailcus = "";
                this.typecus = "";
                this.senper = false;
            }
        } else {
            try {
                this.idcus = Integer.parseInt(SessionProvider.getSessionMapValue("idcus").toString());
                this.emailcus = SessionProvider.getSessionMapValue("emailcus").toString();
                this.typecus = SessionProvider.getSessionMapValue("typecus").toString();
            } catch (Exception e) {
                System.out.println("D:-- sendmail to person: " + e.getMessage());
                this.idcus = Integer.parseInt("0");
                this.emailcus = "";
                this.typecus = "";
                this.senper = false;
            }
        }

        Object objide = getRequest().getParameter("ide");
        Object objidq = getRequest().getParameter("idq");
        Object objstatus = getRequest().getParameter("status");
        if (objide != null && objstatus != null) {
            try {
                System.out.println("D:- chuyen trang thai email: id:= " + objide + "Status:= " + objstatus.toString() + " objidq : " + objidq);
                int ide = Integer.parseInt(objide.toString());
                int idq = 0;
                if (objidq != null) {
                    idq = Integer.parseInt(objidq.toString());
                }
                String status = objstatus.toString();
                m575Store.updateM275OneColumn(null, "M275", "FM525", status, "PM275", ide, getLogin().getUserName());
                if (status.equals("D")) {
                    if (objidq != null) {
                        System.out.println("D:- Delete mail !");
                        m575Store.deleteM275(ide, idq, getLogin().getUserName());
                    }

                } else if (status.equals("R")) {
                    if (objidq != null) {
                        System.out.println("D:- restore mail !");
                        m575Store.restoreM275(ide, idq, getLogin().getUserName());
                    }

                }
            } catch (Exception e) {
                System.out.println("D:- Error from chuyen trang thai Email: " + e.getMessage());
            }
        }

        //filter mail
        Object objmailrevice = getRequest().getParameter("mailrevice");
        System.out.println("D:- mailrevice: " + mailrevice);
        if (objmailrevice != null) {
            try {
                this.mailreviceId = Integer.parseInt(objmailrevice.toString().trim());
                SessionProvider.setSessionMapValue("mailreviceid", this.mailreviceId);
            } catch (Exception e) {
            }


        }

        // filter number 
        Object objnumber = getRequest().getParameter("numbermail");
        System.out.println("D:- objnumber: " + objnumber);
        if (objnumber != null) {
            try {
                this.numberMail = Integer.parseInt(objnumber.toString().trim());
                SessionProvider.setSessionMapValue("numberMail", this.numberMail);
            } catch (Exception e) {
            }


        }


        //paging
        int a;
        Object ppage = getRequest().getParameter("p");
        System.out.println("D:- ppage: " + mailrevice);
        if (ppage != null) {
            try {
                a = Integer.parseInt(ppage.toString());
            } catch (Exception ex) {
                a = 1;
            }
            if (a == 1) {
                setCurrent(1);
                setOffset(0);
            } else {
                setCurrent(a);
                setOffset((a - 1) * Limit);
            }

        } else {
            SessionProvider.setSessionMapValue("typeSearchM", null);
            SessionProvider.setSessionMapValue("keySearchM", null);
            setCurrent(1);
            setOffset(0);
        }

    }

    public void listener(UploadEvent event) throws Exception {

        UploadItem item = event.getUploadItem();

        String path = item.getFile().getPath();

        int myIndex = 0;
        int l = path.length();
        for (int i = path.length() - 1; i > 0; i--) {
            if (path.charAt(i) == '\\') {
                myIndex = i;
                break;
            }
        }

        String temp = path.substring(myIndex + 1, l);
        String path2 = path.replaceAll(temp, item.getFileName());

        if ((new File(path2)).exists()) {
            (new File(path2)).delete();
        }

        File file = new File(path);
        file.renameTo(new File(path2));
        File file2 = new File(path2);
        files.add(file2);
        System.out.println(" DANH SACH TAP TIN DINH KEM!");
        for (File filetemp : files) {
            System.out.println("-- " + filetemp.getName() + "--- " + filetemp.getPath());
        }
    }

    public void sendEmail() {
        try {

            System.out.println("D:- mailsend id: " + mailsendId);
            if (checkN850pop) {
                getM250sendId(mailsendId);
                System.out.println("D:- mailsend: " + mailsend);
                System.out.println("D:- mailsend pass: " + mailsendpass);
                System.out.println("D:- sendEmailTo is called !");
                SMTP_AUTH_USER = mailsend;//your email address
                SMTP_AUTH_PWD = mailsendpass;//your password
            } else {
                getQ000SendById(mailsendId);
                System.out.println("D:- mailsend: " + mailsend);
                System.out.println("D:- mailsend pass: " + mailsendpass);
                System.out.println("D:- sendEmailTo is called !");
                SMTP_AUTH_USER = mailsend;//your email address
                SMTP_AUTH_PWD = mailsendpass;//your password
            }


            // senmail authentication yahoo sever
            if (SMTP_AUTH_USER.contains("@yahoo.com") || SMTP_AUTH_USER.contains("@ymail.com")) {
                String host, port;
                Properties props = System.getProperties();
                Session l_session = null;
                host = "smtp.mail.yahoo.com";
                port = "587";

                props.put("mail.smtp.host", host);
                props.put("mail.smtp.auth", "true");
                props.put("mail.debug", "false");
                props.put("mail.smtp.port", port);
                props.put("mail.smtp.starttls.enable", "true");

                l_session = Session.getInstance(props,
                        new javax.mail.Authenticator() {

                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
                            }
                        });

                l_session.setDebug(true); // Enable the debug mode

                MimeMessage message = new MimeMessage(l_session);
                String emailid = SMTP_AUTH_USER;
                message.setFrom(new InternetAddress(emailid));

                int cout = 0;
                String[] tempd = listInfoTo.split(",");
                if (listInfoTo != "") {
                    for (int i = 0; i < tempd.length; i++) {
                        if (tempd[i] != "" && tempd[i].contains("@")) {
                            cout++;
                            message.addRecipient(Message.RecipientType.CC, new InternetAddress(tempd[i].trim()));
                        }

                    }
                }
                // senmail CC to list 
                Address[] addr = null;
                if (listInfoTo != "") {
                    addr = new Address[cout];
                }

                if (listInfoTo != "") {
                    for (int i = 0; i < cout; i++) {
                        addr[i] = new InternetAddress(tempd[i]);
                    }
                }
                MimeMultipart multipart = new MimeMultipart("mixed");
                List<AttachItem> listAttach = new ArrayList<AttachItem>();
                for (int i = 0; i < files.size(); i++) {
                    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                    messageBodyPart1.attachFile(files.get(i).getPath());
                    System.out.println("D:-- attachFile: " + files.get(i).getPath());
                    multipart.addBodyPart(messageBodyPart1);

                    // save file attach in sever
                    try {
                        InputStream is = new FileInputStream(files.get(i));
                        // save attach in sever
                        String url = files.get(i).getName().replaceAll(" ", "");
                        String urlmd5 = Util.createGUID() + "_" + files.get(i).getName().replaceAll(" ", "");
                        File f = new File(ResourcesProvider.getUploadMail() + urlmd5);
                        FileOutputStream fos = new FileOutputStream(f);
                        byte[] buf = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buf)) != -1) {
                            fos.write(buf, 0, bytesRead);
                        }
                        fos.close();
                        AttachItem att = new AttachItem(url, urlmd5);
                        listAttach.add(att);
                    } catch (Exception e) {
                        continue;
                    }

                }
                message.setContent(multipart);
                message.setSubject(subjectMail, "utf-8");
                message.setContent(contentMail, "text/html; charset=utf-8");
                Transport.send(message);
                System.out.println("Message Sent");
                if (listMail != null && listMail.size() > 0) {
                    int roweffect = m575Inf.updateM575By(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), this.getPm575(), 1, subjectMail, this.getMv577(), contentMail, this.getMv579(), Util.toSQLDate(new Date()), 0, "D", mailsend,0, getLogin().getUserName());
                    if (roweffect > 0 && listAttach != null) {
                        for (AttachItem attach : listAttach) {
                            try {
                                m650Store.updateM650(
                                        0, loginSession.getLogin().getModule(), loginSession.getLogin().getCompanyNo(), 0, 0, null, 0,
                                        "", attach.getUrl(), attach.getUrlmd5(),
                                        0,
                                        null, "M575", roweffect, 0, null, "MAIL", 7,
                                        loginSession.getLogin().getUserName());
                            } catch (Exception e) {
                                continue;
                            }
                        }
                    }
                    for (MailItem item : listMail) {
                        if (item.getEmailAddress() != null && item.getEmailAddress() != "" && item.getEmailAddress().contains("@")) {
                            String content = "";
                            content = item.getSex() + ": " + item.getName() + "\n" + contentMail;
                            sendMailBccYAHOO(item.getIditem(), item.getEmailAddress(), subjectMail, content, files, roweffect);
                        }

                    }
                }


                chkMessS = true;
                files.clear();

                //sendmail gmail    
            } else {
                Properties props = new Properties();

                props.put("mail.transport.protocol", "smtps");
                props.put("mail.smtp.host", SMTP_HOST_NAME);
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtps.from", "kakaka@machine");

                Session mailSession = Session.getInstance(props);
                mailSession.setDebug(true);
                Transport transport = mailSession.getTransport();
                System.out.append("---------------1\n");

                MimeMultipart multipart = new MimeMultipart("mixed");
                List<AttachItem> listAttach = new ArrayList<AttachItem>();
                for (int i = 0; i < files.size(); i++) {
                    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                    messageBodyPart1.attachFile(files.get(i).getPath());
                    multipart.addBodyPart(messageBodyPart1);

                    try {
                        InputStream is = new FileInputStream(files.get(i));
                        // save attach in sever
                        String url = files.get(i).getName().replaceAll(" ", "");
                        String urlmd5 = Util.createGUID() + "_" + files.get(i).getName().replaceAll(" ", "");
                        File f = new File(ResourcesProvider.getUploadMail() + urlmd5);
                        FileOutputStream fos = new FileOutputStream(f);
                        byte[] buf = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buf)) != -1) {
                            fos.write(buf, 0, bytesRead);
                        }
                        fos.close();
                        AttachItem att = new AttachItem(url, urlmd5);
                        listAttach.add(att);
                    } catch (Exception e) {
                        continue;
                    }

                }

                MimeMessage message = new MimeMessage(mailSession);
                message.setSubject(subjectMail, "utf-8");

                message.setContent(multipart);
//            for (int i = 0; i < listMail.size(); i++) {
//                if (listMail.get(i).getEmailAddress() != null && listMail.get(i).getEmailAddress() != "" && listMail.get(i).getEmailAddress().contains("@") ){
//                    message.addRecipient(Message.RecipientType.BCC, new InternetAddress(listMail.get(i).getEmailAddress()));
//                }
//            }
                int cout = 0;
                String[] tempd = listInfoTo.split(",");
                if (listInfoTo != "") {
                    for (int i = 0; i < tempd.length; i++) {
                        if (tempd[i] != "" && tempd[i].contains("@")) {
                            cout++;
                            message.addRecipient(Message.RecipientType.CC, new InternetAddress(tempd[i].trim()));
                        }

                    }
                }


                transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
                System.out.append("---------------2\n");

                // senmail CC to list 
                Address[] addr = null;
                if (listInfoTo != "") {
                    addr = new Address[cout];
                }

                if (listInfoTo != "") {
                    for (int i = 0; i < cout; i++) {
                        addr[i] = new InternetAddress(tempd[i]);
                    }
                }

//            MimeBodyPart textMBCC = new MimeBodyPart();
//
//            
//            System.out.append("---------------3\n");
//            int checksendmail = 0;
//            for (MailItem item : listMail) {
//                if (item.getEmailAddress() != null && item.getEmailAddress() != "" && item.getEmailAddress().contains("@")) {
//                    textMBCC.setContent(item.getSex() + ": " + item.getName() + "\n" + contentMail, "text/html; charset=utf-8");
//                    multipart.addBodyPart(textMBCC);
//                    Address[] s = new Address[1];
//                    s[0] = new InternetAddress(item.getEmailAddress());
//                    transport.sendMessage(message, s);
//                    checksendmail = 1;
//                }
//
//            }
                MimeBodyPart textCC = new MimeBodyPart();
                if (addr != null && addr.length > 0) {
                    textCC.setContent(contentMail, "text/html; charset=utf-8");
                    multipart.addBodyPart(textCC);
                    transport.sendMessage(message, addr);
                }

                transport.close();

                int roweffect = m575Inf.updateM575By(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), this.getPm575(), 1, subjectMail, this.getMv577(), contentMail, this.getMv579(), Util.toSQLDate(new Date()), 0, "D", mailsend,0, getLogin().getUserName());
                if (roweffect > 0 && listAttach != null) {
                    for (AttachItem attach : listAttach) {
                        try {
                            m650Store.updateM650(
                                    0, loginSession.getLogin().getModule(), loginSession.getLogin().getCompanyNo(), 0, 0, null, 0,
                                    "", attach.getUrl(), attach.getUrlmd5(),
                                    0,
                                    null, "M575", roweffect, 0, null, "MAIL", 7,
                                    loginSession.getLogin().getUserName());
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
                for (MailItem item : getListMail()) {
                    if (item.getEmailAddress() != null && item.getEmailAddress() != "" && item.getEmailAddress().contains("@")) {
                        String content = "";
                        content = item.getSex() + ": " + item.getName() + "\n" + contentMail;
                        sendMailBcc(item.getIditem(), item.getEmailAddress(), subjectMail, content, files, roweffect);
                    }

                }

                chkMessS = true;
                files.clear();
//            showGlobalReport(true, getResourceString("senmailsuccessful"));
//            sendRedirect(getPageRequest()+".jsp");
            }


        } catch (Exception e) {
            System.out.println("--D: Error from sendmail: " + e.getMessage());
            chkMess = true;
//            showGlobalReport(true, getResourceString("senmailfail"));
//            sendRedirect(getPageRequest()+".jsp");
        }
    }

    public void sendMailBcc(int idcus, String email, String subject, String content, ArrayList<File> files, int roweffect) {
        try {
            if (checkN850pop) {
                getM250sendId(mailsendId);
                System.out.println("D:- mailsend: " + mailsend);
                System.out.println("D:- mailsend pass: " + mailsendpass);
                System.out.println("D:- sendEmailTo is called !");
                SMTP_AUTH_USER = mailsend;//your email address
                SMTP_AUTH_PWD = mailsendpass;//your password
            } else {
                getQ000SendById(mailsendId);
                System.out.println("D:- mailsend: " + mailsend);
                System.out.println("D:- mailsend pass: " + mailsendpass);
                System.out.println("D:- sendEmailTo is called !");
                SMTP_AUTH_USER = mailsend;//your email address
                SMTP_AUTH_PWD = mailsendpass;//your password
            }

            Properties props = new Properties();

            props.put("mail.transport.protocol", "smtps");
            props.put("mail.smtp.host", SMTP_HOST_NAME);
            props.put("mail.smtps.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtps.from", "kakaka@machine");

            Session mailSession = Session.getInstance(props);
            mailSession.setDebug(true);
            Transport transport = mailSession.getTransport();
            System.out.append("---------------1\n");

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject, "utf-8");

            MimeMultipart multipart = new MimeMultipart("mixed");

            for (int i = 0; i < files.size(); i++) {
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                messageBodyPart1.attachFile(files.get(i).getPath());
                multipart.addBodyPart(messageBodyPart1);
            }
            message.setContent(multipart);

            message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));

            transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
            System.out.append("---------------2\n");

            MimeBodyPart textMBCC = new MimeBodyPart();
            textMBCC.setContent(content, "text/html; charset=utf-8");
            multipart.addBodyPart(textMBCC);
            Address[] st = new Address[1];
            st[0] = new InternetAddress(email);
            transport.sendMessage(message, st);

            transport.close();

            // save mail 
            if (roweffect > 0) {
                m575Inf.updateM275(0, roweffect, idcus, "A", "TO", "D", "S", 0, mailsend, getLogin().getUserName());
            }




        } catch (Exception e) {
            System.out.println("--D: Error from sendmailBCC: " + e.getMessage());
            chkMess = true;
        }
    }

    public void sendMailBccYAHOO(int idcus, String email, String subject, String content, ArrayList<File> files, int roweffect) {
        try {
            if (checkN850pop) {
                getM250sendId(mailsendId);
                System.out.println("D:- mailsend: " + mailsend);
                System.out.println("D:- mailsend pass: " + mailsendpass);
                System.out.println("D:- sendEmailTo is called !");
                SMTP_AUTH_USER = mailsend;//your email address
                SMTP_AUTH_PWD = mailsendpass;//your password
            } else {
                getQ000SendById(mailsendId);
                System.out.println("D:- mailsend: " + mailsend);
                System.out.println("D:- mailsend pass: " + mailsendpass);
                System.out.println("D:- sendEmailTo is called !");
                SMTP_AUTH_USER = mailsend;//your email address
                SMTP_AUTH_PWD = mailsendpass;//your password
            }
            String host, port;
            Properties props = System.getProperties();
            Session l_session = null;
            host = "smtp.mail.yahoo.com";
            port = "587";

            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "false");
            props.put("mail.smtp.port", port);
            props.put("mail.smtp.starttls.enable", "true");

            l_session = Session.getInstance(props,
                    new javax.mail.Authenticator() {

                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
                        }
                    });

            l_session.setDebug(true); // Enable the debug mode

            MimeMessage message = new MimeMessage(l_session);
            String emailid = SMTP_AUTH_USER;
            message.setFrom(new InternetAddress(emailid));
            message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));
            MimeMultipart multipart = new MimeMultipart("mixed");

            for (int i = 0; i < files.size(); i++) {
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                messageBodyPart1.attachFile(files.get(i).getPath());
                multipart.addBodyPart(messageBodyPart1);
            }
            message.setContent(multipart);
            message.setSubject(subject, "utf-8");
            message.setContent(contentMail, "text/html; charset=utf-8");
            Transport.send(message);
            System.out.println("Message Sent");

            // save mail 
            if (roweffect > 0) {
                m575Inf.updateM275(0, roweffect, idcus, "A", "TO", "D", "S", 0, mailsend, getLogin().getUserName());
            }


        } catch (Exception e) {
            System.out.println("--D: Error from sendmailBCC: " + e.getMessage());
            chkMess = true;
        }
    }

    // Search nhân viên trong form công ty TÙNG
    public void reloadform(ActionEvent event) {
        System.out.println("---------------------AADD-------" + keysearchKH + getTypesearchKH());
        SessionProvider.setSessionMapValue("KEYKH", keysearchKH);// tim kiếm lahcsh hang cho cong ty
    }

    public void actionListenner() {

        System.out.println("D:-- filetemp : " + getFiletemp());
        int a = Integer.parseInt(getFiletemp());
        if (a == 1) {
            contentMail = "----------------tempalte 1 -------------";
        } else if (a == 2) {
            contentMail = "----------------tempalte 2 -------------";
        } else if (a == 3) {
            contentMail = "----------------tempalte 2 -------------";
        }
    }

    public List<SelectItem> getSelectItemB050() {
        return comboxUtil.getListCombB050();
    }

    public List<SelectItem> getSelectItemQ100() {
        try {
            return comboxUtil.getListCombQ100();
        } catch (Exception ex) {
            return null;
        }
    }

    public List<M575> getListM275(String mv276, int pnFM575) {
        List<M575> listM275;
        System.out.println("D:- mailsend id: " + mailsendId);
        getQ000SendById(mailsendId);
        System.out.println("D:- mailsend: " + mailsend);
        System.out.println("D:- mailsend pass: " + mailsendpass);
        System.out.println("D:- sendEmailTo is called !");
//            SMTP_AUTH_USER = getLogin().getQv117();//your email address
//            SMTP_AUTH_PWD = getLogin().getQv118();//your password
//            System.out.println("Username : " + getLogin().getQv117());
//            System.out.println("Password : " + getLogin().getQv118());
        SMTP_AUTH_USER = mailsend;//your email address
        SMTP_AUTH_PWD = mailsendpass;//your password
        if (getLogin() != null) {
            int idx = getLogin().getId();
            System.out.println("list--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "I" + "," + getLogin().getUserName());
            try {
                listM275 = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, "A", mv276, "I", mailsend, Offset, Limit, 0, 0, getLogin().getUserName());

            } catch (Exception ex) {
                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
                listM275 = new ArrayList<M575>();
            }
        } else {
            System.out.println("D: -- Error from getListM275: ");
            sendRedirect("login.jsp");
            listM275 = new ArrayList<M575>();
        }
        if (Offset == 0) {
            if (listM275.size() > 0) {
                M575 m575 = listM275.get(0);
                if (m575 != null) {
                    SessionProvider.setSessionMapValue("totalcurentM", m575.getRowss());
                    //totalcurent = n100.getRowss();
                } else {
                    SessionProvider.setSessionMapValue("totalcurentM", 0);
                    //totalcurent = 0;
                }
            } else {
                SessionProvider.setSessionMapValue("totalcurentM", 0);
                //totalcurent = 0;
            }
        }

        //paging
        int t;
        Object obj = SessionProvider.getSessionMapValue("totalcurentM");
        if (obj != null) {
            try {
                t = Integer.parseInt(obj.toString());
            } catch (Exception e) {
                t = 0;
            }
            totalcurent = t;
        } else {
            totalcurent = 0;
        }

        setTotalrow(totalcurent);

        return listM275;
    }

//    public List<M575> getListM275(String mv276, int pnFM575, String fm525) {
//        System.out.println("D:- mailsend id: " + mailsendId);
//        getQ000SendById(mailsendId);
//        System.out.println("D:- mailsend: " + mailsend);
//        System.out.println("D:- mailsend pass: " + mailsendpass);
//        System.out.println("D:- sendEmailTo is called !");
////            SMTP_AUTH_USER = getLogin().getQv117();//your email address
////            SMTP_AUTH_PWD = getLogin().getQv118();//your password
////            System.out.println("Username : " + getLogin().getQv117());
////            System.out.println("Password : " + getLogin().getQv118());
//        SMTP_AUTH_USER = mailsend;//your email address
//        SMTP_AUTH_PWD = mailsendpass;//your password
//        if (getLogin() != null) {
//            int idx = getLogin().getId();
//            System.out.println("list--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "I" + "," + getLogin().getUserName());
//            try {
//                List<M575> listM275TO = new ArrayList<M575>();
//                listM275TO = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "TO", "I", getLogin().getUserName());
//                if (listM275TO != null) {
//                    List<M575> listM275FROM = new ArrayList<M575>();
//                    listM275FROM = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "FROM", "I", getLogin().getUserName());
//                    for (M575 m575 : listM275FROM) {
//                        listM275TO.add(m575);
//                    }
//                }
//                return listM275TO;
//            } catch (Exception ex) {
//                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
//                return new ArrayList<M575>();
//            }
//        } else {
//            System.out.println("D: -- Error from getListM275: ");
//            sendRedirect("login.jsp");
//            return new ArrayList<M575>();
//        }
//
//    }
    public List<M575> getListM275Ex(String mv276, int pnFM575) {
        List<M575> listM275;
        System.out.println("D:-getListM275Ex is called ! ");
        System.out.println("D:-getListM275Ex mailreviceId : " + getMailreviceId());
        System.out.println("checkN850: " + getCheckN850());
        if (getCheckN850()) {
            System.err.println("D:-DANH SACH MAIL PHONG BAN ! ");
            getM250ReviceById(getMailreviceId());
            System.out.println("D:- mailsend: " + mailrevice);
            System.out.println("D:- mailsend pass: " + mailrevicepass);
        } else {
            System.err.println("D:-DANH SACH MAIL CA NHAN ! ");
            getQ000ReviceById(getMailreviceId());
            System.out.println("D:- mailsend: " + mailrevice);
            System.out.println("D:- mailsend pass: " + mailrevicepass);
        }

        if (getLogin() != null) {
            int idx = getLogin().getId();

            try {
                if (getCheckN850()) {
                    System.err.println("DANH SACH MAIL PHONG BAN");
                    System.out.println("m575Store.getListTabM275(" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + 0 + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "D" + "," + mailrevice + " , " + "," + Offset + " , " + "," + Limit + " , " + getLogin().getUserName());
                    listM275 = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), 0, pnFM575, this.getFm525(), mv276, "D", mailrevice, Offset, Limit, 0, 0, getLogin().getUserName());
                } else {
                    System.err.println("DANH SACH MAIL CA NHAN");
                    System.out.println("m575Store.getListTabM275(" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + mv276 + "," + "D" + "," + mailrevice + " , " + "," + Offset + " , " + "," + Limit + " , " + getLogin().getUserName());
                    listM275 = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), mv276, "D", mailrevice, Offset, Limit, 0, 0, getLogin().getUserName());
                }

            } catch (Exception ex) {
                System.out.println("D: -- Error from getListM275: " + ex.getMessage());
                listM275 = new ArrayList<M575>();
            }
        } else {
            System.out.println("D: -- Error from getListM275: ");
            sendRedirect("login.jsp");
            listM275 = new ArrayList<M575>();
        }
        if (Offset == 0) {
            if (listM275.size() > 0) {
                M575 m575 = listM275.get(0);
                if (m575 != null) {
                    SessionProvider.setSessionMapValue("totalcurentM1", m575.getRowss());
                    //totalcurent = n100.getRowss();
                } else {
                    SessionProvider.setSessionMapValue("totalcurentM1", 0);
                    //totalcurent = 0;
                }
            } else {
                SessionProvider.setSessionMapValue("totalcurentM1", 0);
                //totalcurent = 0;
            }
        }

        //paging
        int t;
        Object obj = SessionProvider.getSessionMapValue("totalcurentM1");
        if (obj != null) {
            try {
                t = Integer.parseInt(obj.toString());
            } catch (Exception e) {
                t = 0;
            }
            totalcurent = t;
        } else {
            totalcurent = 0;
        }
        System.out.println("totalcurent: " + totalcurent);
        setTotalrow(totalcurent);

        return listM275;
    }

    public void changen850(ActionEvent ac) {
        System.out.println("D:---change change4ldv " + checkN850);
        if (checkN850) {
            SessionProvider.setSessionMapValue("checkN850", 1);
        } else {
            SessionProvider.setSessionMapValue("checkN850", 0);
        }



    }

    public void changeNumberMail(ActionEvent ac) {
        System.out.println("D:--- changeNumberMail " + numberMail);
    }

    public void changen850pop(ActionEvent ac) {
        System.out.println("D:---change change4ldv " + checkN850pop);
        if (checkN850pop) {
            SessionProvider.setSessionMapValue("checkN850pop", 1);
        } else {
            SessionProvider.setSessionMapValue("checkN850pop", 0);
        }



    }

    public List<M575> getListM275Ex(String mv276, int pnFM575, String fm525) {
        System.out.println("D:-getListM275Ex is called ! ");
        System.out.println("D:-getListM275Ex mailreviceId : " + getMailreviceId());
        getQ000ReviceById(getMailreviceId());
        System.out.println("D:- mailsend: " + mailrevice);
        System.out.println("D:- mailsend pass: " + mailrevicepass);
        if (getLogin() != null) {
            int idx = getLogin().getId();
            System.out.println("list--->" + getLogin().getModule() + "," + getLogin().getCompanyNo() + "," + this.getFb050() + "," + idx + "," + pnFM575 + " , " + this.getFm525() + "," + "TO" + "D" + "," + mailrevice + "," + getLogin().getUserName());
            try {
                List<M575> listM275TO = new ArrayList<M575>();
                listM275TO = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "TO", "D", mailrevice, getLogin().getUserName());
                if (listM275TO != null) {
                    List<M575> listM275FROM = new ArrayList<M575>();
                    listM275FROM = m575Store.getListTabM275D(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, pnFM575, this.getFm525(), "FROM", "D", mailrevice, getLogin().getUserName());
                    for (M575 m575 : listM275FROM) {
                        listM275TO.add(m575);
                    }
                }
                return listM275TO;
            } catch (Exception ex) {
                System.out.println("D: -- Error from getListM275Ex: " + ex.getMessage());
                return new ArrayList<M575>();
            }
        } else {
            System.out.println("D: -- Error from getListM275: ");
            sendRedirect("login.jsp");
            return new ArrayList<M575>();
        }

    }

    public void actionListenner(ActionEvent evt) {
        String come_person = "";
        Iterator ic = comboxUtil.getListCombQ100().iterator();
        while (ic.hasNext()) {
            SelectItem item = (SelectItem) ic.next();

            if (this.getFq100() == Integer.parseInt(item.getValue().toString())) {
                System.out.println("---------m851----------" + item.getValue() + "----------" + item.getLabel());
                getMap().put(this.getFq100(), item.getLabel());
            }
        }
        listSendMail = new ArrayList(map.entrySet());
        if (listSendMail != null) {
            stylefrommail = "block";
        } else {
            stylefrommail = "none";
        }
        Iterator icMap = map.entrySet().iterator();
        while (icMap.hasNext()) {
            Map.Entry mapEntry = (Map.Entry) icMap.next();
            come_person += mapEntry.getValue();
            come_person += ",";
            System.out.println("--vvvvvvvvvvvvvvvvvvv--" + come_person + "-----------vkey--" + mapEntry.getKey());

        }
        //setMv576(come_person);


    }

    /**
     * @return the fb050
     */
    public int getFb050() {
        return fb050;
    }

    /**
     * @param fb050 the fb050 to set
     */
    public void setFb050(int fb050) {
        this.fb050 = fb050;
    }

    /**
     * @return the m575Inf
     */
    public M575Inf getM575Inf() {
        return m575Inf;
    }

    /**
     * @param m575Inf the m575Inf to set
     */
    public void setM575Inf(M575Inf m575Inf) {
        this.m575Inf = m575Inf;
    }

    /**
     * @return the pm575
     */
    public int getPm575() {
        return pm575;
    }

    /**
     * @param pm575 the pm575 to set
     */
    public void setPm575(int pm575) {
        this.pm575 = pm575;
    }

    /**
     * @return the ff150
     */
    public int getFf150() {
        return ff150;
    }

    /**
     * @param ff150 the ff150 to set
     */
    public void setFf150(int ff150) {
        this.ff150 = ff150;
    }

    /**
     * @return the mv576
     */
    public String getMv576() {
        return mv576;
    }

    /**
     * @param mv576 the mv576 to set
     */
    public void setMv576(String mv576) {
        this.mv576 = mv576;
    }

    /**
     * @return the mv577
     */
    public String getMv577() {
        return mv577;
    }

    /**
     * @param mv577 the mv577 to set
     */
    public void setMv577(String mv577) {
        this.mv577 = mv577;
    }

    /**
     * @return the mv578
     */
    public String getMv578() {
        return mv578;
    }

    /**
     * @param mv578 the mv578 to set
     */
    public void setMv578(String mv578) {
        this.mv578 = mv578;
    }

    /**
     * @return the mv579
     */
    public String getMv579() {
        return mv579;
    }

    /**
     * @param mv579 the mv579 to set
     */
    public void setMv579(String mv579) {
        this.mv579 = mv579;
    }

    /**
     * @return the md580
     */
    public Date getMd580() {
        return md580;
    }

    /**
     * @param md580 the md580 to set
     */
    public void setMd580(Date md580) {
        this.md580 = md580;
    }

    /**
     * @return the mn581
     */
    public int getMn581() {
        return mn581;
    }

    /**
     * @param mn581 the mn581 to set
     */
    public void setMn581(int mn581) {
        this.mn581 = mn581;
    }

    /**
     * @return the fh000
     */
    public int getFh000() {
        return fh000;
    }

    /**
     * @param fh000 the fh000 to set
     */
    public void setFh000(int fh000) {
        this.fh000 = fh000;
    }

    /**
     * @return the fh200
     */
    public int getFh200() {
        return fh200;
    }

    /**
     * @param fh200 the fh200 to set
     */
    public void setFh200(int fh200) {
        this.fh200 = fh200;
    }

    /**
     * @return the reload
     */
    public String getReload() {
        return reload;
    }

    /**
     * @param reload the reload to set
     */
    public void setReload(String reload) {
        this.reload = reload;
    }

    /**
     * @return the intreload
     */
    public int getIntreload() {
        return intreload;
    }

    /**
     * @param intreload the intreload to set
     */
    public void setIntreload(int intreload) {
        this.intreload = intreload;
    }

    /**
     * @return the map
     */
    public Map<Integer, String> getMap() {
        return map;
    }

    /**
     * @param map the map to set
     */
    public void setMap(Map<Integer, String> map) {
        this.map = map;
    }

    /**
     * @return the listSendMail
     */
    public List<Map.Entry<Integer, String>> getListSendMail() {
        return listSendMail;
    }

    /**
     * @param listSendMail the listSendMail to set
     */
    public void setListSendMail(List<Map.Entry<Integer, String>> listSendMail) {
        this.listSendMail = listSendMail;
    }

    /**
     * @return the fq100
     */
    public int getFq100() {
        return fq100;
    }

    /**
     * @param fq100 the fq100 to set
     */
    public void setFq100(int fq100) {
        this.fq100 = fq100;
    }

    /**
     * @return the fm525
     */
    public String getFm525() {
        return fm525;
    }

    /**
     * @param fm525 the fm525 to set
     */
    public void setFm525(String fm525) {
        this.fm525 = fm525;
    }

    /**
     * @return the mv276
     */
    public String getMv276() {
        return mv276;
    }

    /**
     * @param mv276 the mv276 to set
     */
    public void setMv276(String mv276) {
        this.mv276 = mv276;
    }

    /**
     * @return the mv277
     */
    public String getMv277() {
        return mv277;
    }

    /**
     * @param mv277 the mv277 to set
     */
    public void setMv277(String mv277) {
        this.mv277 = mv277;
    }

    /**
     * @return the listToFromMail
     */
    /**
     * @param listToFromMail the listToFromMail to set
     */
    public void setListToFromMail(List<M575> listToFromMail) {
        this.listToFromMail = listToFromMail;
    }

    /**
     * @return the hoten
     */
    public String getHoten() {
        return hoten;
    }

    /**
     * @param hoten the hoten to set
     */
    public void setHoten(String hoten) {
        this.hoten = hoten;
    }

    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return the html
     */
    public String getHtml() {
        return html;
    }

    /**
     * @param html the html to set
     */
    public void setHtml(String html) {
        this.html = html;
    }

    /**
     * @return the text
     */
    public String getText() {
        return text;
    }

    /**
     * @param text the text to set
     */
    public void setText(String text) {
        this.text = text;
    }

    /**
     * @return the sendtime
     */
    public Date getSendtime() {
        return sendtime;
    }

    /**
     * @param sendtime the sendtime to set
     */
    public void setSendtime(Date sendtime) {
        this.sendtime = sendtime;
    }

    /**
     * @return the renderMail
     */
    public int getRenderMail() {
        return renderMail;
    }

    /**
     * @param renderMail the renderMail to set
     */
    public void setRenderMail(int renderMail) {
        this.renderMail = renderMail;
    }

    /**
     * @return the loginGmailYahoo
     */
    public String getLoginGmailYahoo() {
        return loginGmailYahoo;
    }

    /**
     * @param loginGmailYahoo the loginGmailYahoo to set
     */
    public void setLoginGmailYahoo(String loginGmailYahoo) {
        this.loginGmailYahoo = loginGmailYahoo;
    }

    /**
     * @return the passwordGmailYahoo
     */
    public String getPasswordGmailYahoo() {
        return passwordGmailYahoo;
    }

    /**
     * @param passwordGmailYahoo the passwordGmailYahoo to set
     */
    public void setPasswordGmailYahoo(String passwordGmailYahoo) {
        this.passwordGmailYahoo = passwordGmailYahoo;
    }

    /**
     * @return the listItemMail
     */
    public List<ItemMail> getListItemMail() {

        return listItemMail;
    }

    /**
     * @param listItemMail the listItemMail to set
     */
    public void setListItemMail(List<ItemMail> listItemMail) {
        this.listItemMail = listItemMail;
    }

    /**
     * @return the fromMail
     */
    public String getFromMail() {
        return fromMail;
    }

    /**
     * @param fromMail the fromMail to set
     */
    public void setFromMail(String fromMail) {
        this.fromMail = fromMail;
    }

    /**
     * @return the toMail
     */
    public String getToMail() {
        return toMail;
    }

    /**
     * @param toMail the toMail to set
     */
    public void setToMail(String toMail) {
        this.toMail = toMail;
    }

    /**
     * @return the dateSend
     */
    public String getDateSend() {
        return dateSend;
    }

    /**
     * @param dateSend the dateSend to set
     */
    public void setDateSend(String dateSend) {
        this.dateSend = dateSend;
    }

    /**
     * @return the titleMail
     */
    public String getTitleMail() {
        return titleMail;
    }

    /**
     * @param titleMail the titleMail to set
     */
    public void setTitleMail(String titleMail) {
        this.titleMail = titleMail;
    }

    /**
     * @return the content
     */
    public String getContent() {
        return content;
    }

    /**
     * @param content the content to set
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @return the listitem
     */
    public List<ItemMail> getListitem() {
        listitem = (List<ItemMail>) SessionProvider.getSessionMapValue("listitem");
        return listitem;
    }

    /**
     * @param listitem the listitem to set
     */
    public void setListitem(List<ItemMail> listitem) {
        this.listitem = listitem;
    }

    /**
     * @return the colorchose
     */
    public String getColorchose() {
        return colorchose;
    }

    /**
     * @param colorchose the colorchose to set
     */
    public void setColorchose(String colorchose) {
        this.colorchose = colorchose;
    }

    /**
     * @return the stylefrommail
     */
    public String getStylefrommail() {
        return stylefrommail;
    }

    /**
     * @param stylefrommail the stylefrommail to set
     */
    public void setStylefrommail(String stylefrommail) {
        this.stylefrommail = stylefrommail;
    }

    /**
     * @return the subjectMail
     */
    public String getSubjectMail() {
        return subjectMail;
    }

    /**
     * @param subjectMail the subjectMail to set
     */
    public void setSubjectMail(String subjectMail) {
        this.subjectMail = subjectMail;
    }

    /**
     * @return the contentMail
     */
    public String getContentMail() {
        return contentMail;
    }

    /**
     * @param contentMail the contentMail to set
     */
    public void setContentMail(String contentMail) {
        this.contentMail = contentMail;
    }

    /**
     * @return the methodSend
     */
    public String getMethodSend() {
        return methodSend;
    }

    /**
     * @param methodSend the methodSend to set
     */
    public void setMethodSend(String methodSend) {
        this.methodSend = methodSend;
    }

    /**
     * @return the listInfo
     */
    public String getListInfo() {
        return listInfo;
    }

    /**
     * @param listInfo the listInfo to set
     */
    public void setListInfo(String listInfo) {
        this.listInfo = listInfo;
    }

    /**
     * @return the listMail
     */
    public List<MailItem> getListMail() {
        List<N100> listKH = new ArrayList<N100>();
        Object listselected = SessionProvider.getSessionMapValue("listSelectedMail");
        if (listselected != null) {
            try {
                listKH = (List<N100>) listselected;
            } catch (Exception e) {
                listKH = new ArrayList<N100>();
            }
        } else {
            listKH = new ArrayList<N100>();
        }

        for (int i = 0; i < listKH.size(); i++) {
            N100 cus = listKH.get(i);
            if (cus.getNv120() != null && cus.getNv120() != "" && cus.getNv120().contains("@")) {
                MailItem mail = new MailItem(cus.pn100, cus.getHoten(), cus.getNv120(), "", cus.getPronouns(), "");
                listMail.add(mail);
//                    listInfo += listKH.get(i).getNv105() + ";  ";
            }

        }
        return listMail;
    }

    /**
     * @param listMail the listMail to set
     */
    public void setListMail(List<MailItem> listMail) {
        this.listMail = listMail;
    }

    /**
     * @return the listInfoTo
     */
    public String getListInfoTo() {
        List<N100> listKH = new ArrayList<N100>();
        Object listselected = SessionProvider.getSessionMapValue("listSelectedMail");
        if (listselected != null) {
            try {
                listKH = (List<N100>) listselected;
            } catch (Exception e) {
                listKH = new ArrayList<N100>();
            }
        } else {
            listKH = new ArrayList<N100>();
        }

        for (int i = 0; i < listKH.size(); i++) {
            N100 cus = listKH.get(i);
            if (cus.getNv105() != null && cus.getNv105() != "" && cus.getNv105().contains("@")) {
                MailItem mail = new MailItem(cus.pn100, cus.getHoten(), cus.getNv105(), "", cus.getPronouns(), "");
//                    listMail.add(mail);
                listInfo += listKH.get(i).getNv105() + ";  ";
            }

        }
        return listInfoTo;
    }

    /**
     * @param listInfoTo the listInfoTo to set
     */
    public void setListInfoTo(String listInfoTo) {
        this.listInfoTo = listInfoTo;
    }

    /**
     * @return the s
     */
    public String getS() {
        return s;
    }

    /**
     * @param s the s to set
     */
    public void setS(String s) {
        this.s = s;
    }

    /**
     * @return the chkMess
     */
    public Boolean getChkMess() {
        return chkMess;
    }

    /**
     * @param chkMess the chkMess to set
     */
    public void setChkMess(Boolean chkMess) {
        this.chkMess = chkMess;
    }

    /**
     * @return the chkMessS
     */
    public Boolean getChkMessS() {
        return chkMessS;
    }

    /**
     * @param chkMessS the chkMessS to set
     */
    public void setChkMessS(Boolean chkMessS) {
        this.chkMessS = chkMessS;
    }

    /**
     * @return the filetemp
     */
    public String getFiletemp() {
        return filetemp;
    }

    /**
     * @param filetemp the filetemp to set
     */
    public void setFiletemp(String filetemp) {
        this.filetemp = filetemp;
    }

    /**
     * @return the idcus
     */
    public int getIdcus() {
        return idcus;
    }

    /**
     * @param idcus the idcus to set
     */
    public void setIdcus(int idcus) {
        this.idcus = idcus;
    }

    /**
     * @return the emailcus
     */
    public String getEmailcus() {
        return emailcus;
    }

    /**
     * @param emailcus the emailcus to set
     */
    public void setEmailcus(String emailcus) {
        this.emailcus = emailcus;
    }

    /**
     * @return the typecus
     */
    public String getTypecus() {
        return typecus;
    }

    /**
     * @param typecus the typecus to set
     */
    public void setTypecus(String typecus) {
        this.typecus = typecus;
    }

    /**
     * @return the senper
     */
    public Boolean getSenper() {
        return senper;
    }

    /**
     * @param senper the senper to set
     */
    public void setSenper(Boolean senper) {
        this.senper = senper;
    }

    /**
     * @return the pageRequest
     */
    public String getPageRequest() {
        return pageRequest;
    }

    /**
     * @param pageRequest the pageRequest to set
     */
    public void setPageRequest(String pageRequest) {
        this.pageRequest = pageRequest;
    }

    /**
     * @return the mailBox
     */
    public String getMailBox() {
//        if (mv276.equals("TO")) {
//            mailBox = "Hộp thư đến";
//        } else if (mv276.equals("FROM")) {
//            mailBox = "Thư đã gửi";
//        }
        if (SessionProvider.getSessionMapValue("mailBox") != null) {
            mailBox = SessionProvider.getSessionMapValue("mailBox").toString();
        }
        return mailBox;
    }

    /**
     * @param mailBox the mailBox to set
     */
    public void setMailBox(String mailBox) {
        this.mailBox = mailBox;
    }

    /**
     * @return the listToFromMailEx
     */
    public List<M575> getListToFromMailEx() {

        System.out.println("So luong mail can lay: " + getNumberMail());
        try {
            if (getSttTitle() == 1) {
                System.out.println("D:- Danh sach mail Họp thu den !");
                listToFromMailEx = getListToFromMailSever();
            } else if (getSttTitle() == 2) {
                System.out.println("D:- Danh sach mail Họp thu di !");
                listToFromMailEx = getListM275Ex("FROM", 0);
            } else if (getSttTitle() == 3) {
                System.out.println("D:- Danh sach mail Thu bị xoa !");
                listToFromMailEx = getListM275Ex(null, 0, null);
            }
        } catch (Exception e) {
            System.err.println("Error from getListToFromMailEx: " + e.getMessage());
            listToFromMailEx = new ArrayList<M575>();
        }

        return listToFromMailEx;
    }

    /**
     * @param listToFromMailEx the listToFromMailEx to set
     */
    public void setListToFromMailEx(List<M575> listToFromMailEx) {
        this.listToFromMailEx = listToFromMailEx;
    }

    /**
     * @return the check
     */
    public String getCheck() {
        return check;
    }

    /**
     * @param check the check to set
     */
    public void setCheck(String check) {
        this.check = check;
    }

    /**
     * @return the sttTitle
     */
    public int getSttTitle() {
        if (SessionProvider.getSessionMapValue("sttTitle") != null) {
            sttTitle = Integer.parseInt(SessionProvider.getSessionMapValue("sttTitle").toString());
        }
        return sttTitle;
    }

    /**
     * @param sttTitle the sttTitle to set
     */
    public void setSttTitle(int sttTitle) {
        this.sttTitle = sttTitle;
    }

    public void changeAll(ActionEvent ac) {
        System.out.println("D:------------------------------------------------------abc");
    }

    public void change4ldv(ActionEvent ac) {
        List<M200> list = m200Store.getListM200All(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getId(), getLogin().getUserName());
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getPm200() == getPm200()) {
                    this.contentMail = (list.get(i).getMv202());
                    break;
                }
            }
        }

    }

//    public void changelist(ActionEvent ac) {
//        System.out.println("D:-changelist is called ! ");
//        System.out.println("D:-changelist mailreviceId : " + mailreviceId);
//        getQ000ReviceById(mailreviceId);
//        System.out.println("D:- mailsend: " + mailrevice);
//        System.out.println("D:- mailsend pass: " + mailrevicepass);
//        
//        SessionProvider.setSessionMapValue("Exmailrevice", mailrevice);
//
//
//    }
    /**
     * @return the pm200
     */
    public int getPm200() {
        return pm200;
    }

    /**
     * @param pm200 the pm200 to set
     */
    public void setPm200(int pm200) {
        this.pm200 = pm200;
    }

    /**
     * @return the listmail
     */
    public String getListmail() {
        Object obj = SessionProvider.getSessionMapValue("listSelectedMail");
        if (obj != null) {
            listmail = "";
            try {
                List<N100> list = (List<N100>) obj;
                if (list != null && list.size() > 0) {
                    for (N100 n100 : list) {
                        listmail += n100.getHoten() + "; ";

                    }
                }
            } catch (Exception e) {
                listmail = "";
            }
        }
        System.out.println("D:- Danh sach: " + listmail);
        return listmail;
    }

    /**
     * @param listmail the listmail to set
     */
    public void setListmail(String listmail) {
        this.listmail = listmail;
    }

    /**
     * @return the listcomboM200
     */
    public List<SelectItem> getListcomboM200() {
        listcomboM200 = comboxUtil.getlistCombM200();
        return listcomboM200;
    }

    /**
     * @param listcomboM200 the listcomboM200 to set
     */
    public void setListcomboM200(List<SelectItem> listcomboM200) {
        this.listcomboM200 = listcomboM200;
    }

    public void getQ000SendById(int pq000) {
        Q000Store q000Store = new Q000Store();
        List<Q000> lst = q000Store.getListQ000(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getId(), getLogin().getUserName());
        if (lst != null) {
            System.out.println("D:- list getListAllQ000ByIDofMyprofile: " + lst.size());
        } else {
            System.out.println("D:- list getListAllQ000ByIDofMyprofile: null");
        }
        for (Q000 q000 : lst) {
            if (q000.getPQ000() == pq000) {
                this.mailsend = q000.getQV001();
                this.mailsendpass = q000.getQV002();
            }
        }
    }

    public void getQ000ReviceById(int pq000) {
        Q000Store q000Store = new Q000Store();
        List<Q000> lst = q000Store.getListQ000(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getId(), getLogin().getUserName());
        if (lst != null) {
            System.out.println("D:- list getListAllQ000ByIDofMyprofile: " + lst.size());
            for (Q000 q000 : lst) {
                if (q000.getPQ000() == pq000) {
                    this.mailrevice = q000.getQV001();
                    this.mailrevicepass = q000.getQV002();
                }
            }
        } else {
            System.out.println("D:- list getListAllQ000ByIDofMyprofile: null");
        }

    }

    public void getM250ReviceById(int pm250) {
        try {
            M250Store m250Store = new M250Store();
            List<M250> lst = m250Store.getListM250(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getFn850(), getLogin().getUserName());
            if (lst != null && lst.size() > 0) {
                System.out.println("D:- list getM250ReviceById: " + lst.size());
                for (M250 m250 : lst) {
                    if (m250.getPm250() == pm250) {
                        this.mailrevice = m250.getMv251();
                        this.mailrevicepass = m250.getMv255();
                    }
                }
            } else {
                System.out.println("D:- list getM250ReviceById: null");
            }
        } catch (Exception e) {
            System.err.println("D: erro from getM250ReviceById: " + e.getMessage());
        }


    }

    public void getM250sendId(int pm250) {
        try {
            M250Store m250Store = new M250Store();
            List<M250> lst = m250Store.getListM250(getLogin().getModule(), getLogin().getCompanyNo(), getLogin().getFn850(), getLogin().getUserName());
            if (lst != null && lst.size() > 0) {
                System.out.println("D:- list getM250ReviceById: " + lst.size());
                for (M250 m250 : lst) {
                    if (m250.getPm250() == pm250) {
                        this.mailsend = m250.getMv251();
                        this.mailsendpass = m250.getMv255();
                    }
                }
            } else {
                System.out.println("D:- list getM250ReviceById: null");
            }
        } catch (Exception e) {
            System.err.println("D: erro from getM250ReviceById: " + e.getMessage());
        }


    }

    public List<M575> getListToFromMailSever() {
        System.out.println("D:-getListToFromMailSever is called ! ");
        System.out.println("D:-getListToFromMailSever mailreviceId : " + getMailreviceId());
        if (getCheckN850()) {
            System.err.println("D:- DANH SACH MAIL PHONG BAN");
            getM250ReviceById(getMailreviceId());
            System.out.println("D:- mailsend: " + mailrevice);
            System.out.println("D:- mailsend pass: " + mailrevicepass);
        } else {
            System.err.println("D:- DANH SACH MAIL CA NHAN");
            getQ000ReviceById(getMailreviceId());
            System.out.println("D:- mailsend: " + mailrevice);
            System.out.println("D:- mailsend pass: " + mailrevicepass);
        }


        List<File> attachments = new ArrayList<File>();
        Properties props = System.getProperties();

        String host = "pop.gmail.com";

        final String username = (getLogin() != null) ? mailrevice : "";

        final String password = (getLogin() != null) ? mailrevicepass : "";

        String provider = "pop3s";
        try {
            // chi get mail tu sever lan dau
            if (Offset == 0) {

                String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
                props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
                props.setProperty("mail.pop3.socketFactory.fallback", "false");
                props.setProperty("mail.pop3.port", "995");
                props.setProperty("mail.pop3.socketFactory.port", "995");
                props.put("mail.pop3.host", "pop.gmail.com");
                props.put("mail.smtp.host", "pop.gmail.com");
                props.put("mail.smtp.port", "587");
                props.put("mail.smtp.starttls.enable", "true");

                javax.mail.Authenticator pa = null; //default: no authentication

                if (username != null && password != null) {

                    props.put("mail.smtp.auth", "true");

                    pa = new javax.mail.Authenticator() {

                        public PasswordAuthentication getPasswordAuthentication() {

                            return new PasswordAuthentication(username, password);

                        }
                    };

                }//else: no authentication

                // Kết nối đến POP3 server

                Session session = Session.getInstance(props, pa);

                Store store = session.getStore(provider);

                store.connect(host, username, password);

                // Mở thư mục INBOX

                Folder inbox = store.getFolder("inbox");

                if (inbox == null) {

                    System.out.println("No INBOX");

                    System.exit(1);

                }
                inbox.open(Folder.READ_ONLY);


                // Lấy messages từ server
//            Message messages[] = inbox.getMessages();

                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

                Message messages[] = inbox.search(ft);
                FetchProfile fp = new FetchProfile();
                fp.add(FetchProfile.Item.ENVELOPE);
                fp.add(FetchProfile.Item.CONTENT_INFO);
                inbox.fetch(messages, fp);

                if (messages.length < 1 || messages == null) {
                    System.out.println("Không có mail mới nào cả!");
                } else {
                    System.out.println("Số lương Mail: " + messages.length);
                    if (messages.length < getNumberMail()) {
                        SessionProvider.setSessionMapValue("numberMail",  messages.length);
                    }
                    System.out.println("So recode can lay: " + getNumberMail());
                    for (int messageCount = 0; messageCount < getNumberMail(); messageCount++) {
                        messages[messageCount].setFlag(Flags.Flag.SEEN, true);
                        String from = messages[messageCount].getFrom()[0].toString().trim();
                        String fromcv = Util.removeQuotes(from).trim();
//                    System.out.println("From: -"+from+"-");
//                    System.out.println("Fromcv: -"+fromcv+"-");
//                    System.out.println("username: -"+username+"-");
//                    System.out.println("from.equals(username) : "+ from.equals(username));
//                    System.out.println("fromcv.equals(username) : "+ fromcv.equals(username));
//                    System.out.println("username.equals(fromcv) : "+ username.equals(fromcv));
                        if (username.equals(fromcv)) {
                            continue;
                        }
                        List<AttachItem> listAttach = new ArrayList<AttachItem>();
                        System.out.println("Mail number : " + messages[messageCount].getMessageNumber());
                        try {
                            Message aMessage = messages[messageCount];
                            String senderAddress = aMessage.getFrom()[0].toString();
                            String subject = aMessage.getSubject();
                            String mv582 = Util.getCodeTour(subject);
                            System.err.println("D:------------------code tour: " + mv582);

                            // parses recipient address in To field
                            String toAddresses = "";
                            Address[] listTO = aMessage.getRecipients(Message.RecipientType.TO);
                            if (listTO != null) {
                                for (int toCount = 0; toCount < listTO.length; toCount++) {
                                    toAddresses += listTO[toCount].toString() + ", ";
                                }
                            }
                            if (toAddresses.length() > 1) {
                                toAddresses = toAddresses.substring(0, toAddresses.length() - 2);
                            }

                            // parses recipient addresses in CC field
                            String ccAddresses = "";
                            Address[] listCC = aMessage.getRecipients(Message.RecipientType.CC);
                            if (listCC != null) {
                                for (int ccCount = 0; ccCount < listCC.length; ccCount++) {
                                    ccAddresses = listCC[ccCount].toString() + ", ";
                                }
                            }
                            if (ccAddresses.length() > 1) {
                                ccAddresses = ccAddresses.substring(0, ccAddresses.length() - 2);
                            }

                            Date sentDate = aMessage.getSentDate();

                            String contentType = aMessage.getContentType();
                            String textMessage = "";
                            String attachFiles = "";
//                System.out.println("D:- contentType: " + contentType);
                            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                                textMessage = aMessage.getContent() != null ? aMessage.getContent().toString() : "";
                            } else if (contentType.contains("multipart/")) {
                                MimeMultipart multiPart = (MimeMultipart) aMessage.getContent();
                                int numberOfParts = multiPart.getCount();
                                for (int partCount = 0; partCount < numberOfParts; partCount++) {

                                    try {
                                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                                        String contentMail = getText(part);
                                        System.out.println("String :" + contentMail);
                                        if (contentMail != null && !contentMail.equals("")) {
                                            textMessage = contentMail;
                                        }
                                        BodyPart bodyPart = multiPart.getBodyPart(partCount);
                                        if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                                            continue; // dealing with attachments only
                                        }
                                        InputStream is = bodyPart.getInputStream();
//                        File f = new File("D:/" + bodyPart.getFileName());
                                        System.out.println();
                                        //String s = ResourcesProvider.getUploadMail() + Util.createGUID() + "_" + bodyPart.getFileName().replaceAll(" ", "");
                                        //System.out.println("Path: " + s);
                                        String url = bodyPart.getFileName().replaceAll(" ", "");
                                        String urlmd5 = Util.createGUID() + "_" + bodyPart.getFileName().replaceAll(" ", "");
                                        File f = new File(ResourcesProvider.getUploadMail() + urlmd5);
                                        FileOutputStream fos = new FileOutputStream(f);
                                        byte[] buf = new byte[4096];
                                        int bytesRead;
                                        while ((bytesRead = is.read(buf)) != -1) {
                                            fos.write(buf, 0, bytesRead);
                                        }
                                        fos.close();
                                        AttachItem att = new AttachItem(url, urlmd5);
                                        listAttach.add(att);
                                        attachments.add(f);
                                    } catch (Exception e) {
                                        System.out.println("Error from read mail:" + e.getMessage());
                                        continue;
                                    }


                                }

                            }

                            System.out.println("D:- Call save mail !");
                            System.out.println("m575Store.updateM575SEVERN(" + 7 + " , " + 99 + " , " + subject + " , " + null + " , " + textMessage + " , " + null + " , " + Util.toSQLDate(sentDate) + " , " + 0 + " , " + mv582 + " , " + "D" + " , " + Util.removeQuotes(senderAddress) + " , " + mailrevice + " , " + getLogin().getUserName());
                            int pm575 = m575Store.updateM575SEVERN(7, 99, subject, null, textMessage, null, Util.toSQLDate(sentDate), 0, mv582, "D", Util.removeQuotes(senderAddress), mailrevice,0, getLogin().getUserName());
                            System.out.println("Email is save!");
                            if (pm575 > 0 && listAttach != null) {
                                for (AttachItem attach : listAttach) {
                                    try {
                                        m650Store.updateM650(
                                                0, loginSession.getLogin().getModule(), loginSession.getLogin().getCompanyNo(), 0, 0, null, 0,
                                                "", attach.getUrl(), attach.getUrlmd5(),
                                                0,
                                                null, "M575", pm575, 0, null, "MAIL", 7,
                                                loginSession.getLogin().getUserName());
                                    } catch (Exception e) {
                                        continue;
                                    }
                                }
                            }
                        } catch (Exception e) {
                            continue;
                        }

                    }
                    inbox.close(true);
                    store.close();
                    System.out.println("Inbox is close ! -- store is close !");
                }

            }

        } catch (Exception ex) {
            System.out.println("D:- Error from get mail sever: " + ex.getMessage());
            ex.printStackTrace();
//            listToFromMailSever = new ArrayList<M575>();
            showGlobalReport(true, "Không lấy được Mail từ sever !");


        } finally {
            //get listmail
            if (getLogin() != null) {
                int idx = getLogin().getId();
                try {
                    if (getCheckN850()) {
                        System.err.print("D: DANH SACH  MAIL TU SEVER CHO MAIL PHONG BAN");
                        System.out.println("m575Store.getListTabM275(" + getLogin().getModule() + " ," + getLogin().getCompanyNo() + " ," + this.getFb050() + " ," + 0 + " ," + 0 + " ," + this.getFm525() + " ," + "TO" + " ," + "D" + " ," + mailrevice + " ," + " ," + Offset + " ," + " ," + Limit + " ," + getLogin().getUserName() + " )");
                        listToFromMailSever = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), 0, 0, this.getFm525(), "TO", "D", mailrevice, Offset, Limit, 0, 0, getLogin().getUserName());
                    } else {
                        System.err.print("D: DANH SACH  MAIL TU SEVER CHO MAIL CA NHAN");
                        System.out.println("m575Store.getListTabM275(" + getLogin().getModule() + " ," + getLogin().getCompanyNo() + " ," + this.getFb050() + " ," + idx + " ," + 0 + " ," + this.getFm525() + " ," + "TO" + " ," + "D" + " ," + mailrevice + " ," + " ," + Offset + " ," + " ," + Limit + " ," + getLogin().getUserName() + " )");
                        listToFromMailSever = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, 0, this.getFm525(), "TO", "D", mailrevice, Offset, Limit, 0, 0, getLogin().getUserName());
                    }

//                    listToFromMailSever = m575Store.getListTabM275(getLogin().getModule(), getLogin().getCompanyNo(), this.getFb050(), idx, 0, this.getFm525(), mv276, "D", mailrevice, getLogin().getUserName());
//                    return listToFromMailSever;
                } catch (Exception ex) {
                    System.out.println("D: -- Error from getListM275: " + ex.getMessage());
                    listToFromMailSever = new ArrayList<M575>();
                }
            } else {
                System.out.println("D: -- Error from getListM275: ");
//            sendRedirect("login.jsp");
                listToFromMailSever = new ArrayList<M575>();
            }

        }

        if (Offset == 0) {
            if (listToFromMailSever.size() > 0) {
                M575 m575 = listToFromMailSever.get(0);
                if (m575 != null) {
                    SessionProvider.setSessionMapValue("totalcurentM", m575.getRowss());
                    //totalcurent = n100.getRowss();
                } else {
                    SessionProvider.setSessionMapValue("totalcurentM", 0);
                    //totalcurent = 0;
                }
            } else {
                SessionProvider.setSessionMapValue("totalcurentM", 0);
                //totalcurent = 0;
            }
        }

        //paging
        int t;
        Object obj = SessionProvider.getSessionMapValue("totalcurentM");
        if (obj != null) {
            try {
                t = Integer.parseInt(obj.toString());
            } catch (Exception e) {
                t = 0;
            }
            totalcurent = t;
        } else {
            totalcurent = 0;
        }

        setTotalrow(totalcurent);

        return listToFromMailSever;
    }

    /**
     * @param listToFromMailSever the listToFromMailSever to set
     */
    public void setListToFromMailSever(List<M575> listToFromMailSever) {
        this.listToFromMailSever = listToFromMailSever;
    }

    /**
     * @return the keysearchKH
     */
    public String getKeysearchKH() {
        return keysearchKH;
    }

    /**
     * @param keysearchKH the keysearchKH to set
     */
    public void setKeysearchKH(String keysearchKH) {
        this.keysearchKH = keysearchKH;
    }

    /**
     * @return the typesearchKH
     */
    public int getTypesearchKH() {
        return typesearchKH;
    }

    /**
     * @param typesearchKH the typesearchKH to set
     */
    public void setTypesearchKH(int typesearchKH) {
        this.typesearchKH = typesearchKH;
    }

    /**
     * @return the listdifn100
     */
    // Lít nhân vien
    public List<N100> getListdifn100() {
        try {
            CustomerStore store = new CustomerStore();
            if (SessionProvider.getSessionMapValue("KEYKH") != null) {
                keysearchKH = SessionProvider.getSessionMapValue("KEYKH").toString();
                listdifn100 = store.getListCustomer_NA(getLogin().getModule(), getLogin().getCompanyNo(), keysearchKH, 0, 1000, 0, 0, getLogin().getUserName());
                System.out.println("----list222222---------- " + listdifn100.size());
            } else {
                listdifn100 = store.getListN100DifK100(getLogin().getModule(), getLogin().getCompanyNo(), 0, 0, 1, 30, getLogin().getUserName());
                System.out.println("----list " + listdifn100.size());
            }
            SessionProvider.setSessionMapValue("listN100abc", listdifn100);
            return listdifn100;

        } catch (Exception e) {
            System.out.println("D:- Error from getListdifn100 (lay danh sach nhan vien): " + e.getMessage());
            return new ArrayList<N100>();
        }

    }

    /**
     * @param listdifn100 the listdifn100 to set
     */
    public void setListdifn100(List<N100> listdifn100) {
        this.listdifn100 = listdifn100;
    }

    /**
     * @return the listSelected
     */
    public List<N100> getListSelected() {
        return listSelected;
    }

    /**
     * @param listSelected the listSelected to set
     */
    public void setListSelected(List<N100> listSelected) {
        this.listSelected = listSelected;
    }

    public void readContent(Object o) throws IOException, MessagingException {
        if (o instanceof String) {
            System.out.println("**This is a String Message**");
            System.out.println((String) o);
        } else if (o instanceof Multipart) {
            System.out.print("**This is a Multipart Message.  ");
            Multipart mp = (Multipart) o;
            int count3 = mp.getCount();
            System.out.println("It has " + count3
                    + " BodyParts in it**");
            for (int j = 0; j < count3; j++) {
                // Part are numbered starting at 0
                BodyPart b = mp.getBodyPart(j);
                String mimeType2 = b.getContentType();
                System.out.println("BodyPart " + (j + 1) + " is of MimeType " + mp.getContentType());

                Object o2 = b.getContent();
                if (o2 instanceof String) {
                    System.out.println("**This is a String BodyPart**");
                    System.out.println((String) o2);
                } else if (o2 instanceof Multipart) {
                    System.out.print(
                            "**This BodyPart is a nested Multipart.  ");
                    Multipart mp2 = (Multipart) o2;
                    int count2 = mp2.getCount();
                    System.out.println("It has " + count2
                            + "further BodyParts in it**");
                } else if (o2 instanceof InputStream) {
                    System.out.println(
                            "**This is an InputStream BodyPart**");
                }
            } //End of for
        } else if (o instanceof InputStream) {
            System.out.println("**This is an InputStream message**");
            InputStream is = (InputStream) o;
            // Assumes character content (not binary images)
            int c;
            while ((c = is.read()) != -1) {
                System.out.write(c);
            }
        }
    }
    private boolean textIsHtml = false;

    public String getText(Part p) throws
            MessagingException, IOException {
        if (p.isMimeType("text/*")) {
            String s = (String) p.getContent();
            textIsHtml = p.isMimeType("text/html");
            return s;
        }

        if (p.isMimeType("multipart/alternative")) {
            // prefer html text over plain text
            Multipart mp = (Multipart) p.getContent();
            String text = null;
            for (int i = 0; i < mp.getCount(); i++) {
                Part bp = mp.getBodyPart(i);
                if (bp.isMimeType("text/plain")) {
                    if (text == null) {
                        text = getText(bp);
                    }
                    continue;
                } else if (bp.isMimeType("text/html")) {
                    String s = getText(bp);
                    if (s != null) {
                        return s;
                    }
                } else {
                    return getText(bp);
                }
            }
            return text;
        } else if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();

            // Dump input stream ..
            InputStream is = p.getInputStream();
            // If "is" is not already buffered, wrap a BufferedInputStream
            // around it.
            if (!(is instanceof BufferedInputStream)) {
                is = new BufferedInputStream(is);
            }
            int c;
            System.out.println("Message : ");
            while ((c = is.read()) != -1) {
                System.out.write(c);
            }


            for (int i = 0; i < mp.getCount(); i++) {
                String s = getText(mp.getBodyPart(i));
                if (s != null) {
                    return s;
                }
            }
        }

        return null;
    }

    /**
     * @return the mailsend
     */
    public String getMailsend() {
        return mailsend;
    }

    /**
     * @param mailsend the mailsend to set
     */
    public void setMailsend(String mailsend) {
        this.mailsend = mailsend;
    }

    /**
     * @return the mailsendId
     */
    public int getMailsendId() {
        return mailsendId;
    }

    /**
     * @param mailsendId the mailsendId to set
     */
    public void setMailsendId(int mailsendId) {
        this.mailsendId = mailsendId;
    }

    /**
     * @return the mailsendpass
     */
    public String getMailsendpass() {
        return mailsendpass;
    }

    /**
     * @param mailsendpass the mailsendpass to set
     */
    public void setMailsendpass(String mailsendpass) {
        this.mailsendpass = mailsendpass;
    }

    /**
     * @return the mailrevice
     */
    public String getMailrevice() {
        return mailrevice;
    }

    /**
     * @param mailrevice the mailrevice to set
     */
    public void setMailrevice(String mailrevice) {
        this.mailrevice = mailrevice;
    }

    /**
     * @return the mailreviceId
     */
    public int getMailreviceId() {
        if (SessionProvider.getSessionMapValue("mailreviceid") != null) {
            mailreviceId = Integer.parseInt(SessionProvider.getSessionMapValue("mailreviceid").toString().trim());
        }
        return mailreviceId;
    }

    /**
     * @param mailreviceId the mailreviceId to set
     */
    public void setMailreviceId(int mailreviceId) {
        this.mailreviceId = mailreviceId;
    }

    /**
     * @return the mailrevicepass
     */
    public String getMailrevicepass() {
        return mailrevicepass;
    }

    /**
     * @param mailrevicepass the mailrevicepass to set
     */
    public void setMailrevicepass(String mailrevicepass) {
        this.mailrevicepass = mailrevicepass;
    }

    /**
     * @return the listcomboQ000
     */
    public List<SelectItem> getListcomboQ000() {
        try {
            listcomboQ000 = comboxUtil.getListComboQ000();
        } catch (Exception e) {
            System.out.println("D:- error from getListcomboQ000: " + e.getMessage());
        }
        return listcomboQ000;
    }

    /**
     * @param listcomboQ000 the listcomboQ000 to set
     */
    public void setListcomboQ000(List<SelectItem> listcomboQ000) {
        this.listcomboQ000 = listcomboQ000;
    }

    /**
     * @return the Offset
     */
    public int getOffset() {
        return Offset;
    }

    /**
     * @param Offset the Offset to set
     */
    public void setOffset(int Offset) {
        this.Offset = Offset;
    }

    /**
     * @return the Limit
     */
    public int getLimit() {
        return Limit;
    }

    /**
     * @param Limit the Limit to set
     */
    public void setLimit(int Limit) {
        this.Limit = Limit;
    }

    // property for paging
    /**
     * @return the current
     */
    public int getCurrent() {
        if (current > totalpage) {
            current = totalpage;
        } else if (current < 1) {
            current = 1;
        }
        return current;
    }

    /**
     * @param current the current to set
     */
    public void setCurrent(int current) {

        start = (current - 1) * getNumrow();
        end = current * numrow;
        this.current = current;
    }

    /**
     * @return the numrow
     */
    public int getNumrow() {
        if (numrow == 0) {
            numrow = 30;
        }
        return numrow;
    }

    /**
     * @param numrow the numrow to set
     */
    public void setNumrow(int numrow) {
        this.numrow = numrow;
    }

    /**
     * @return the start
     */
    public int getStart() {
        if (start == 0) {
            start = 1;
        }
        return start;
    }

    /**
     * @param start the start to set
     */
    public void setStart(int start) {
        this.start = start;
    }

    /**
     * @return the end
     */
    public int getEnd() {
        if (end == 0) {
            end = 20;
        }
        return end;
    }

    /**
     * @param end the end to set
     */
    public void setEnd(int end) {
        this.end = end;
    }

    /**
     * @return the totalrow
     */
    public int getTotalrow() {
        return totalrow;
    }

    /**
     * @param totalrow the totalrow to set
     */
    public void setTotalrow(int totalrow) {
//        if (totalrow == 0) {
//            totalrow = 100;
//        }
        totalpage = totalrow / numrow;

        if (totalrow % numrow > 0) {
            totalpage = totalpage + 1;
        }


        if (getTotalpage() <= 10) {
            setStartpage(1);
            setEndpage(getTotalpage());

        } else {
            setStartpage(current - 5);
            setEndpage(current + 5);


        }
        this.totalrow = totalrow;
    }

    /**
     * @return the startpage
     */
    public int getStartpage() {
        if (startpage < 1) {
            startpage = 1;
        }
        return startpage;
    }

    /**
     * @param startpage the startpage to set
     */
    public void setStartpage(int startpage) {
        this.startpage = startpage;
    }

    /**
     * @return the endpage
     */
    public int getEndpage() {
        if (endpage > totalpage) {
            endpage = totalpage;
        }
        return endpage;
    }

    /**
     * @param endpage the endpage to set
     */
    public void setEndpage(int endpage) {

        this.endpage = endpage;
    }

    /**
     * @return the totalpage
     */
    public int getTotalpage() {
//        if (totalpage == 0) {
//            totalpage = 10;
//        }
        return totalpage;
    }

    /**
     * @param totalpage the totalpage to set
     */
    public void setTotalpage(int totalpage) {
        this.totalpage = totalpage;
    }

    /**
     * @return the pagename
     */
    public String getPagename() {
        return pagename;
    }

    /**
     * @param pagename the pagename to set
     */
    public void setPagename(String pagename) {
        this.pagename = pagename;
    }

    /**
     * @return the totalcurent
     */
    public int getTotalcurent() {
        return totalcurent;
    }

    /**
     * @param totalcurent the totalcurent to set
     */
    public void setTotalcurent(int totalcurent) {
        this.totalcurent = totalcurent;
    }

    /**
     * @return the listcomboM250
     */
    public List<SelectItem> getListcomboM250() {
        try {
            listcomboM250 = comboxUtil.getListComboM250();
        } catch (Exception e) {
            System.out.println("D:- error from listcomboM250: " + e.getMessage());
        }
        return listcomboM250;
    }

    /**
     * @param listcomboM250 the listcomboM250 to set
     */
    public void setListcomboM250(List<SelectItem> listcomboM250) {
        this.listcomboM250 = listcomboM250;
    }

    /**
     * @return the checkN850
     */
    public Boolean getCheckN850() {
        if (SessionProvider.getSessionMapValue("checkN850") != null) {
            try {
                int n = Integer.parseInt(SessionProvider.getSessionMapValue("checkN850").toString().trim());
                if (n == 1) {
                    checkN850 = true;
                } else {
                    checkN850 = false;
                }
            } catch (Exception e) {
                checkN850 = false;
            }

        }
        return checkN850;
    }

    /**
     * @param checkN850 the checkN850 to set
     */
    public void setCheckN850(Boolean checkN850) {
        this.checkN850 = checkN850;
    }

    /**
     * @return the checkN850
     */
    public Boolean getCheckN850pop() {
        if (SessionProvider.getSessionMapValue("checkN850pop") != null) {
            try {
                int n = Integer.parseInt(SessionProvider.getSessionMapValue("checkN850pop").toString().trim());
                if (n == 1) {
                    checkN850pop = true;
                } else {
                    checkN850pop = false;
                }
            } catch (Exception e) {
                checkN850pop = false;
            }

        }
        return checkN850pop;
    }

    /**
     * @param checkN850 the checkN850 to set
     */
    public void setCheckN850pop(Boolean checkN850) {
        this.checkN850pop = checkN850;
    }

    /**
     * @return the numberMail
     */
    public int getNumberMail() {
        if (SessionProvider.getSessionMapValue("numberMail") != null) {
            try {
                numberMail = Integer.parseInt(SessionProvider.getSessionMapValue("numberMail").toString());
            } catch (Exception e) {
                System.out.println("D:- error from getNumberMail: " + e.getMessage());
            }

        }
        return numberMail;
    }

    /**
     * @param numberMail the numberMail to set
     */
    public void setNumberMail(int numberMail) {
        this.numberMail = numberMail;
    }
}
